#include "Connection.h"

Connection::Connection(EventLoop *loop, Sock *clientSock)
    : loop_(loop), clientSock_(clientSock)
{
    clientChannel_ = new Channel(loop_, clientSock->getSock());
    clientChannel_->setReadCallBack(std::bind(&Channel::onmessage, clientChannel_));
    clientChannel_->setCloseCallBack(std::bind(&Connection::closecallback, this));
    clientChannel_->setErrorCallBack(std::bind(&Connection::errorcallback, this));
    clientChannel_->useET();
    clientChannel_->enableReading();
}
Connection::~Connection()
{
    delete clientSock_;
    delete clientChannel_;
}

std::string Connection::getIp() const
{
    return clientSock_->getIp();
}
uint16_t Connection::getPort() const
{
    return clientSock_->getPort();
}

int Connection::getFd() const
{
    // std::cout<<"Connection::getFd() begin"<<std::endl;
    return clientSock_->getSock();
    // std::cout<<"Connection::getFd( end"<<std::endl;
}

void Connection::closecallback()
{
    // printf("client(eventfd=%d) disconnected.\n", getFd());
    // close(getFd()); // 关闭客户端的fd。
    closeCallBack_(this);
}
void Connection::errorcallback()
{
    // printf("client(eventfd=%d) error.\n", getFd());
    // close(getFd()); // 关闭客户端的fd。
    errorCallBack_(this);
}

void Connection::setCloseCallBack(func_t fn)
{
    closeCallBack_ = fn;
}
void Connection::setErrorCallBack(func_t fn)
{
    
    errorCallBack_ = fn;
}